package com.Jano.util;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

public class RandomUtils {
    private static final int WIDTH = 160;
    private static final int HEIGHT = 40;
    private static final int CODE_OFFSET_X = 40;
    private static final int CODE_OFFSET_Y = 20;
    private static final int CODE_FONT_SIZE = 20;
    private static final int NOISE_LINES_COUNT = 8;

    private RandomUtils() {

    }

    /**
     * 生成一个指定长度的随机验证码
     * @param len 验证码的长度
     * @return 含有字母和数字的随机验证码
     */
    public static String generateValidateCode(int len) {
        Random r = new Random();
        String str = "3456789ABCDEFGHMNPQRSTUVWXY";
        String result = "";
        for (int i = 1; i <= len; i++) {
            //[0,N)
            result += str.charAt(r.nextInt(str.length()));
        }
        return result;
    }

    /**
     * 生成一个随机的颜色
     * @return 随机颜色对象
     */
    public static Color randomColor() {
        Random random = new Random();
        return new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256));
    }

    /**
     * 用于在内存画板中绘制随机验证码图片
     * @param code 随机验证码
     * @return 内存中的验证码图片对象，需要将这个对象输出到指定的目的地
     * 可以输出到本地文件，也可以输出到HTTP的响应输出流中
     */
    public static BufferedImage drawValidateCode(String code) {
        Random r = new Random();
        //1.创建一个基于内存的画板对象
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        //2.获取画笔对象
        Graphics g = image.getGraphics();
        //3.绘制验证码的背景色
        g.setColor(RandomUtils.randomColor());
        g.fillRect(0, 0, WIDTH, HEIGHT);
        //4.绘制随机字符串
        g.setColor(RandomUtils.randomColor());
        g.setFont(new Font("", Font.BOLD, CODE_FONT_SIZE));
        g.drawString(code, CODE_OFFSET_X, CODE_OFFSET_Y);
        //5.绘制干扰线（噪音线）
        for (int i = 1; i <= NOISE_LINES_COUNT; i++) {
            g.setColor(RandomUtils.randomColor());
            g.drawLine(r.nextInt(WIDTH), r.nextInt(HEIGHT),
                    r.nextInt(WIDTH), r.nextInt(HEIGHT));
        }
        //TODO:没有直接提供画点的操作，绘制噪音点可以通过设置绘制线条时候的两对坐标一样即可
        return image;
    }
}
